#include<iostream>
#include<cmath>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;

int mincontour(vector<vector<Point>> &);//找出面积最小的轮廓//

int main()
{
    int min;
    Mat src_img;
    Mat hsv_img;
    Mat inrange_img;
    Mat canny_img;
    Mat inrange_img1, inrange_img2;
    Mat dilate_kel = getStructuringElement(MORPH_RECT, Size(3, 3));
    Mat erode_kel = getStructuringElement(MORPH_RECT, Size(13, 13));
    Mat background(700, 700, CV_8U, Scalar(255));
    Rect rect;
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    vector<Rect> boundRect(contours.size());
    Point2f center;
    float radius = 0;
    VideoCapture cap("//home//joker//桌面//视频//3.avi");

    while(true)
    {
        cap >> src_img;
        
        if(!cap.isOpened() || src_img.empty())
        {
            cout << "No video is opened!";
            return 0;
        }

        cvtColor(src_img, hsv_img, COLOR_BGR2HSV);
        inRange(hsv_img, Scalar(0, 43, 46), Scalar(20, 255, 255), inrange_img1);
        inRange(hsv_img, Scalar(156, 43, 46), Scalar(180, 255, 255), inrange_img2);//提取红色//
        //inRange(hsv_img, Scalar(100, 43, 46), Scalar(124, 255, 255), inrange_img);//提取蓝色//
        addWeighted(inrange_img1, 1.0, inrange_img2,  1.0, 0, inrange_img);
        floodFill(inrange_img, Point(3, 3), Scalar(255, 255, 255), &rect, Scalar(1, 1, 1), Scalar(1, 1, 1));//用水漫填充将各部分分离//
        dilate(inrange_img, inrange_img, dilate_kel);//除去噪点//
        erode(inrange_img, inrange_img, erode_kel);//将已经打击的旋转壁各部分联通为一个大部分//
        Canny(inrange_img, canny_img, 100, 200);
        findContours( canny_img, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE); 
        min = mincontour(contours);
        
       if (min != -1)
       {
            minEnclosingCircle(contours[min], center, radius);
            circle(src_img, center, radius, Scalar(255, 255, 255));
            circle(src_img, center, 3, Scalar(255, 0, 0));
       }
        imshow("src_video", src_img);
        cout << center << endl;
        waitKey(20);
        if(cin.get() == '1')
        {
            imwrite("test0.png", src_img);
        }
    }
        return 0;
}

int mincontour(vector<vector<Point>> &contours)
{
    int min = -1;
    float min_area = 20000;
    float current_area;
    for(int i = 0; i < contours.size(); i++)
    {
        current_area = contourArea(contours[i]);
        if(current_area < min_area && current_area > 1000 && current_area < 2000)//筛选面积//
        {
            min = i;
            min_area = current_area;
        }
    }
    return min;
}

